package org.leumasjaffe.initiativeTracker.distributed.controller;

import static org.leumasjaffe.initiativeTracker.operator.InitiativeController.tracker;

import java.util.ArrayList;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.leumasjaffe.initiativeTracker.Constants;
import org.leumasjaffe.initiativeTracker.operator.CharacterDecoder;
import org.leumasjaffe.initiativeTracker.operator.CharacterLinker;
import org.leumasjaffe.initiativeTracker.operator.InitiativeController;
import org.leumasjaffe.initiativeTracker.view.InitiativeFrame;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.wpi.heineman.xml.Message;
import edu.wpi.heineman.client.IMessageHandler;

@NonNullByDefault
public class DownloadHandler implements IMessageHandler {

	@SuppressWarnings("null")
	@Override
	public void process(Message response) {
		Node base = response.contents.getFirstChild();
		NamedNodeMap map = base.getAttributes();
		NodeList nl = base.getChildNodes();
		
		String id = map.getNamedItem("game").getNodeValue();
		
		InitiativeController tracker = tracker(id);
		
		tracker.root.setTurnNum(Integer.decode(map.getNamedItem("turn").getNodeValue()));
		tracker.root.setSubTurn(Integer.decode(map.getNamedItem("next").getNodeValue()));
		
		
		tracker.list.setList(new ArrayList<CharacterLinker>());
		if (Constants.client)
			InitiativeFrame.getInstance().init();
		
		for (int i = 0; i < nl.getLength(); i++)
			tracker.list.add(CharacterDecoder.decode(nl.item(i), id));/*
			tracker.list.add(CharacterDecoder.decode(nl.item(i).getAttributes(), id));/**/

		if (Constants.client) {
			try {
				System.out.println("Downloading initiative order...");
				Thread.sleep(1000);
				System.out.println("Download Complete, starting initiativeTracker...\n");
				Thread.sleep(500);
			} catch (Exception e) {}
			InitiativeFrame.getInstance().setUp();
		}

//		if (list.size() > 0)
//			if (list.get(0).getCharacter().getInit() != 0) {
//				root.changeTurn();
//		}
	}

	@Override
	public IMessageHandler newCopy() {
		return new DownloadHandler();
	}

}
